package com.luck.pf.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Serializable;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import org.apache.commons.io.FilenameUtils;

public class FileUtil {
	public static String readFile(String path) throws IOException {
		String content = "";
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(path));
			String line;
			while ((line = reader.readLine()) != null) {
				content += line + "n";
			}
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					// 关闭Reader出现的异常一般不需要处理。
				}
			}
		}
		return content;
	}
	public static void writeResponse(String res, String filePath) {
		try {
			FileOutputStream fos = new FileOutputStream(filePath);
			byte[] bytes = res.getBytes();
			fos.write(bytes);
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static String makePath(String fileName) {
		String path = "d:/workspace/soaptest/data/" + fileName;
		return path;
	}
	/**
     * 文件转化为字节数组
     */
    public static byte[] getBytesFromFile(File f) {
        if (f == null) {
            return null;
        }
        try {
            FileInputStream stream = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1)
                out.write(b, 0, n);
            stream.close();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
        }
        return null;
    }

    /**
     * 把字节数组保存为一个文件
     */
    public static File getFileFromBytes(byte[] b, String outputFile) {
        BufferedOutputStream stream = null;
        File file = null;
        try {
            file = new File(outputFile);
            FileOutputStream fstream = new FileOutputStream(file);
            stream = new BufferedOutputStream(fstream);
            stream.write(b);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return file;
    }

    /**
     * 从字节数组获取对象
     */
    public static Object getObjectFromBytes(byte[] objBytes) throws Exception {
        if (objBytes == null || objBytes.length == 0) {
            return null;
        }
        ByteArrayInputStream bi = new ByteArrayInputStream(objBytes);
        ObjectInputStream oi = new ObjectInputStream(bi);
        return oi.readObject();
    }

    /**
     * 从对象获取一个字节数组
     */
    public static byte[] getBytesFromObject(Serializable obj) throws Exception {
        if (obj == null) {
            return null;
        }
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = new ObjectOutputStream(bo);
        oo.writeObject(obj);
        return bo.toByteArray();
    }
    /**
     * 自动从inputstream里面读数据，然后写到outputstream里面去。
     * @param input inputstream
     * @param output outputstream
     * @param close 读完后是否自动关闭流。
     * */
    public static void write(InputStream input, OutputStream output,boolean close)
            throws IOException {
        byte[] b = new byte[1024];
        int len = input.read(b);
        while (len != -1) {
            output.write(b, 0, len);
            len = input.read(b);
        }
        
        output.flush();
        if (close) {
            input.close();    
            output.close();
        }
    }
	public static String readOracleClob(Clob clob){
		Reader reader = null;
		try {
			reader = clob.getCharacterStream();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		StringBuffer stringBuffer;
		stringBuffer = new StringBuffer();
		try {
			char buffer[] = new char[4096];
			int count = -1;
			for(; ;) {
				count = reader.read(buffer);
				if (count == -1)
					break;
				stringBuffer.append(buffer, 0, count);
			}
		} catch(IOException e) {
			e.printStackTrace();
		}
      
		return stringBuffer.toString();
	}
  public static void mkDir(String dirName)  {
      File dir = null;
      dir = new File(dirName);
      if (!dir.exists()) {
          dir.mkdirs();
      }
  }
  //对于类似服务器上不同磁盘空间做移文件的操作，使用该方法
  public static boolean copyAndDelete(String file, String source, String destination)  {
      File fin = null;
      boolean success = false;

      if (copyFile(file, source, destination)) {
          fin = new File(source, file);
          if (fin.exists()) {
              if (fin.delete()) {
                  success = true;
              }
          }
      }

      return success;
  }

  public static void copyFile (File inFile, File outFile)
      throws Exception
  {
      DataInputStream in = null;
      DataOutputStream out = null;
      if (inFile.isDirectory()) {
          throw new Exception("Not support copy by directory, line 19 in file FileUtil.java");
      }
      try {
          if (inFile.isFile()) {
              in = new DataInputStream(
                  new BufferedInputStream(
                      new FileInputStream(inFile)));
              if (outFile.exists()) {
                  outFile.delete();
              }
              outFile.createNewFile();
              out = new DataOutputStream(
                  new BufferedOutputStream(
                      new FileOutputStream(outFile)));

              byte[] buf = new byte[1024];
              int nums, offset = 0;
              while ( (nums = in.read(buf, offset, 1024)) != -1) {
                  out.write(buf, offset, nums);
              }
              //System.out.println("nums:" + nums);
              out.close();
              in.close();
          }
      } catch (Exception e) {
          out.close();
          in.close();
          throw e;
      }
  }

  public static boolean copyFile (String file, String source, String destination)
  {
      File iFile = null;
      File oFile = null;
      boolean success = false;
      File oDir = new File (destination);
      if (!oDir.exists()) {
    	  oDir.mkdirs();
      }
      iFile = new File(source, file);
      oFile = new File(destination, file);

      try {
          copyFile(iFile, oFile);
          success = true;
      } catch (Exception e) {
          success = false;
          e.printStackTrace();
      }

      return success;
    }
  public static ArrayList getFile(String sPath, int maxDealFile) {
		ArrayList list = new ArrayList();
		ArrayList listTemp = new ArrayList();
		File rootdir = new File(sPath);

		if (rootdir.isDirectory()) {
			File[] filedir = rootdir.listFiles();
			int fileLength = filedir.length;
			if (fileLength > maxDealFile)
				fileLength = maxDealFile;

			for (int i = 0; i < filedir.length; i++) {
				if (filedir[i].isFile())
					listTemp.add(filedir[i]);
				else {
					fileLength--;
				}
			}
			Comparator comp = new FileComparator();
			Collections.sort(listTemp, comp);
			for (int j = 0; j < fileLength; j++) {
//				System.out.println(((File)listTemp.get(j)).getAbsolutePath());
				list.add(((File)listTemp.get(j)).getAbsolutePath());
			}
		} else {
			System.out.println("rootdir:" + rootdir + " 不是目录");
		}

		return list;
	}

	/**
	 * 备份文件
	 * @param file File
	 */
	public static void backupfile(String backupRoot, File file, String fileDir, boolean isDelFile)
      throws Exception {
		try {
			FileInputStream fis = new FileInputStream(file);
			File outFile = new File(backupRoot + "/" + DateUtil.dateToString(DateUtil.getDate(), "yyyy-MM-dd") + "/" + fileDir + "/"
									+ file.getName());
			if (!outFile.getParentFile().exists()) {
				outFile.getParentFile().mkdirs();
			}
			FileOutputStream fos = new FileOutputStream(outFile);
			byte[] buf = new byte[1024];
			int i = 0;
			while ((i = fis.read(buf)) != -1) {
				fos.write(buf, 0, i);
			}
			fis.close();
			fos.close();
			//删除处理后的文件
			if (isDelFile)
				file.delete();
		} catch (Exception ex) {
//			Debug.println("BackUp File Error:" + ex.toString(), 4);
			throw new Exception("BackUp File Error:" + ex.toString());
		}
	}

	public static class FileComparator implements Comparator {
		public int compare(Object element1, Object element2) {
			String lower1 = String.valueOf(((File)element1).lastModified());
			String lower2 = String.valueOf(((File)element2).lastModified());

			return lower1.compareTo(lower2);
		}
	}

	public static void changeUtf8ToGBK(String fstr, String tstr, String backupRoot, String compareRoot) {
		try {
			InputStreamReader fsr = new InputStreamReader(new FileInputStream(fstr), "UTF-8");
			BufferedReader br = new BufferedReader(fsr);
			String line = br.readLine();
			StringBuffer sb = new StringBuffer();
			while (line != null) {
				sb.append(line);
				line = br.readLine();
			}
			String str = sb.toString();
			str = str.substring(1, str.length());
			str = str.replaceAll("utf-8", "GBK");
			sb = new StringBuffer();
			sb.append(str);
			writeFile(sb, tstr);
			fsr.close();
          backupfile(backupRoot, new File(fstr), compareRoot, true);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	  public static void moveFile(String source, String destination)  {
	      File fin, fout;
	      fout = new File(destination);
	      if (!fout.exists()) {
	          fout.mkdirs();
	      }
	      fin = new File(source);
	      fout = new File(destination);
	      if (fout.exists()) fout.delete();
	      fin.renameTo(fout);
	  }

	public static void writeFile(StringBuffer sb, String dst) {
		try {
			FileWriter fw = new FileWriter(new File(dst));
			BufferedWriter wb = new BufferedWriter(fw);
			wb.write(sb.toString());
			wb.flush();
			fw.close();
			wb.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	  public static boolean moveFile (String file, String source, String destination) {
	      File fin, fout;
	      boolean success = false;

	      try {
	          fout = new File(destination);
	          if (!fout.exists()) {
	              fout.mkdirs();
	          }
	          fin = new File(source, file);
	          fout = new File(destination, file);
	          if (fout.exists())fout.delete();
	          if (fin.renameTo(fout)) {
	              success = true;
	          }
	      } catch(Exception e) {
	          success = false;
	          e.printStackTrace();
	      }
	      return success;
	  }
	public static void moveFile(File fin, String destination, String fileName) {
		File  fout;
		fout = new File(destination);
		if (!fout.exists()) {
			fout.mkdirs();
		}
		fout = new File(destination+fileName);
		if (fout.exists())
			fout.delete();
		fin.renameTo(fout);
	}
	/**
	 * @param fin
	 * @param foutdir
	 * @param overwrite
	 */
  public static void copyFile(String fin, String foutdir, boolean overwrite) {
      File inFile = new File(fin);
      File outFile = new File(foutdir + "/" + inFile.getName());
      if (!outFile.getParentFile().exists()) {
          outFile.getParentFile().mkdirs();
      }
      if(overwrite&&outFile.exists())
      	outFile.delete();
      try {

          FileInputStream fis = new FileInputStream(inFile);
          FileOutputStream fos = new FileOutputStream(outFile);
          byte[] buf = new byte[1024];
          int i = 0;

          while ((i = fis.read(buf)) != -1) {
              fos.write(buf, 0, i);
          }
          fis.close();
          fos.close();
		} catch (Exception e) {
			
		}
  }
public static String fileRename(File file) throws Exception{
	// 得到文件路径,包括文件名
	String filePath = file.getPath();
	// 得到文件名
	String filename = FilenameUtils.getName(file.getName());
	//得到路径
	String path = filePath.replace(filename, "");
	// 得到文件名前缀
	String baseName = FilenameUtils.removeExtension(filename);
	// 得到文件名后缀
	String extension = FilenameUtils.getExtension(filename);
	// 得到修改后的文件名
	String reduceFileName = baseName + "_b" + "." + extension;
	// 文件全名
	String fileFullName = path + reduceFileName;
	return fileFullName;
}
	public static void main(String[] args) throws Exception{
		File file = new File("D:/workspace/webphone/WebRoot/audio/10011827222.mp3");
		System.out.println(fileRename(file));
	}

}
